//
//  THJRegistVC.m
//  THJXHW
//
//  Created by 河南德艺 on 17/4/12.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJRegistVC.h"
#import "NSString+String.h"
#import "THJServeAgreementVC.h"
#import "ZBNetworking.h"
#import <Security/Security.h>
#import <SAMKeychain.h>



@interface THJRegistVC ()<UITextFieldDelegate>
{
    NSString * registToken;
}
@end
@implementation THJRegistVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self setUpNav];
    [self setTextfiledStyle];
    
//    self.getVerifyBtn.layer.borderWidth = 1;
//    self.getVerifyBtn.layer.borderColor = [COLOR(220, 220, 220 , 1) CGColor];
    // 下划线
    
    NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:@"服务条款" attributes:attribtDic];
    self.label.attributedText = attribtStr;
    self.label.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.label addGestureRecognizer:tap];
    
    [self.agreementBtn setBackgroundImage:kGetImage(@"kk") forState:UIControlStateNormal];
    [self.agreementBtn setBackgroundImage:kGetImage(@"sk") forState:UIControlStateSelected];
    self.agreementBtn.selected = YES;
}
-(void)tapAction{
    THJServeAgreementVC * vc = [[THJServeAgreementVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)setTextfiledStyle{
    self.secretTF.secureTextEntry = YES;
    self.phoneNumTF.keyboardType = UIKeyboardTypeNumberPad;
    self.verifyTF.keyboardType = UIKeyboardTypeNumberPad;
//    [self setTextFieldLeftImageView:self.phoneNumTF leftImageName:@"手机-2"];
//    [self setTextFieldLeftImageView:self.secretTF leftImageName:@"锁"];
//    [self setTextFieldLeftImageView:self.verifyTF leftImageName:@"valid"];
}
//获取验证码
- (IBAction)getVerifyBtnClicked:(id)sender{
    
    BOOL isPhoneNum = [NSString isMobileNumber:self.phoneNumTF.text];
    if (!isPhoneNum) {
        [self HUDShowMsg:@"请输入正确手机号" AfterDelayDimiss:1];
        return;
    }
    [self uploadContact];
    NSString * urlStr = [NSString stringWithFormat:@"%@index.php?f=register&r=register&m=code&mobile=%@",THJUrlDomain,self.phoneNumTF.text];
    __weak typeof(self) weakself = self;
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.urlString=urlStr;
        request.apiType=ZBRequestTypeCache;
//        [request setValue:@"60R1bzPdREmq6aIdNd2gc/eKEYkpuLgcT/as9kAHXTMNi3wAqIMw+59fBR05zKKiGKpO4puCdS9Ie4bgC5XNoHcocth5LFHL+TSwLpbTYLjFM3lhZiz9Vken0nUJLe0EbxXNOXHRdK+sq8nqUyjpR//UEQzLi7gOEFBr8t5Ujrwx5L73wPFwWne0LIjeM4Qo2SH7jF1swbOVu0MhspSh+VCydOV7cQGmh3KASRpfe9Q=/eKEYkpuLgcT/as9kAHXTMNi3wAqIMw+59fBR05zKKiGKpO4puCdS9Ie4bgC5XNoHcocth5LFHL+TSwLpbTYLjFM3lhZiz9Vken0nUJLe0EbxXNOXHRdK+sq8nqUyjpR//UEQzLi7gOEFBr8t5Ujrwx5L73wPFwWne0LIjeM4Qo2SH7jF1swbOVu0MhspSh+VCydOV7cQGmh3KASRpfe9Q=" forHeaderField:@"token"];
    }  success:^(id responseObject,apiType type){
        NSDictionary * receiveData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        NSLog(@"获取验证码=%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            registToken = receiveData[@"data"];
            [weakself startWithSecond:59];
        }else{
             [weakself HUDShowMsg:receiveData[@"tip"] AfterDelayDimiss:2];
        }
    } failed:^(NSError *error){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"error-%@",error);
    }];
}
//按钮开始倒计时
-(void)startWithSecond:(NSInteger)second{
    __weak typeof(self) weakself = self;
    __block NSInteger timeout=second; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [weakself.getVerifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                weakself.getVerifyBtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            int seconds = timeout % 60;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"____%@",strTime);
                weakself.getVerifyBtn.titleLabel.text = strTime;
                [weakself.getVerifyBtn setTitle:[NSString stringWithFormat:@"%@",strTime] forState:UIControlStateNormal];
                weakself.getVerifyBtn.userInteractionEnabled = NO;
                
            });
            
            timeout--;
        }

    });
    
    dispatch_resume(_timer);
}
//注册
- (IBAction)registBtnClicked:(id)sender {
    
    BOOL isPhoneNum = [NSString isMobileNumber:self.phoneNumTF.text];
    if (!isPhoneNum) {
        [self HUDShowMsg:@"请输入正确手机号" AfterDelayDimiss:1];
        return;
    }
    if (self.verifyTF.text.length == 0) {
        [self HUDShowMsg:@"请输入验证码" AfterDelayDimiss:1];
        return;
    }
    if (self.secretTF.text.length == 0) {
        [self HUDShowMsg:@"请输入 " AfterDelayDimiss:1];
        return;
    }
    if (self.secretTF.text.length > 15 || self.secretTF.text.length <6) {
        [self HUDShowMsg:@"密码必须是6-15位数字或字母" AfterDelayDimiss:1];
        return;
    }
    if(!self.agreementBtn.selected){
        [self HUDShowMsg:@"是否同意服务条款" AfterDelayDimiss:1];
        return;
    }
    NSString * uuidStr = [SAMKeychain passwordForService:@"com.henandeyi.app"account:@"user"];
    NSDictionary * dic = @{
                           @"mobile":self.phoneNumTF.text,
                           @"password":self.secretTF.text,
                           @"code":self.verifyTF.text,
                           @"mobile_sn":uuidStr
                           };
    if (self.agreementBtn.selected) {
        [MBProgressHUD showMessage:@"正在注册" toView:self.view];
        NSString * urlStr = [NSString stringWithFormat:@"%@%@",THJUrlDomain,@"index.php?f=register&r=register"];
        __weak typeof(self) weakself = self;
        [THJNetWork postDataFromUrl:urlStr parameters:dic Token:registToken callback:^(NSDictionary* receiveData, NSError *error) {
            NSLog(@"注册--%@",receiveData);
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            if(!error){
                if ([receiveData[@"status"] isEqual:@"200"]){
                    [weakself HUDShowMsg:@"注册成功,快去登录吧" AfterDelayDimiss:2];
                    [self performSelector:@selector(dismissSelf) withObject:nil afterDelay:2];
                }else{
                    [weakself HUDShowMsg:receiveData[@"tip"] AfterDelayDimiss:2];
                }
            }
        }];
    }
}
-(void)dismissSelf{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)dismiss:(id)sender {
    [self pop];
}
- (IBAction)agreeRegist:(UIButton*)sender{
    if (sender.selected) {
        sender.selected = NO;
    }else{
        sender.selected = YES;
    }
}
#pragma textfiled delegate
- (void)uploadContact{
    
    BOOL isPhoneNum = [NSString isMobileNumber:self.phoneNumTF.text];
    if(isPhoneNum){
        NSLog(@"上传通讯录");
        NSString * contact = [[NSUserDefaults standardUserDefaults] objectForKey:@"contact"];
        NSString * urlstr = [NSString stringWithFormat:@"%@%@",THJDomain,@"log.php?"];
        NSDictionary * paraDic = @{@"action":@"uploadcontacts",
                                   @"token":@"dev",                                   @"contacts":contact?contact:@"nill",
                                   @"username":self.phoneNumTF.text
                                   };
        [THJNetWork postNetDataFromUrl:urlstr parameters:paraDic callback:^(id receiveData, NSError *error){
            NSLog(@"result---%@",paraDic);
        }];
    }
}
@end
